package org.lgiavedoni.android.franq.util.googe;

import java.io.StringBufferInputStream;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.lgiavedoni.android.franq.core.bean.Address;
import org.lgiavedoni.android.franq.core.bean.WeatherCondition;
import org.lgiavedoni.android.franq.core.position.Position;
import org.lgiavedoni.android.franq.service.log.Logger;
import org.lgiavedoni.android.franq.util.network.NetworkUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class WeatherUtil {

	public static WeatherCondition getWheather(Address address) {
		try {
			if (address.getCity() == null)
				return null;
			String xml = NetworkUtil.getResponse(new URL("http://www.google.com/ig/api?weather=" + address.getCity()));
			if (xml != null)
				return parseXML(xml);
		} catch (Exception ex) {
			Logger.inst.error(ex);
		}
		return null;
	}

	public static WeatherCondition getWeather(Position position) {
		return getWheather(GeocodingUtil.getAddress(position));
	}

	private static WeatherCondition parseXML(String xml) {
		WeatherCondition wc = new WeatherCondition();
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(new StringBufferInputStream(xml));
			doc.getDocumentElement().normalize();
			Node node = doc.getElementsByTagName("current_conditions").item(0);
			NodeList nodeLst = node.getChildNodes();
			for (int j = 0; j < nodeLst.getLength(); j++) {
				Node child = nodeLst.item(j);
				String value = child.getAttributes().getNamedItem("data").getNodeValue();
				if ("temp_c".equals(child.getNodeName())) {
					wc.setTempC(value);
				}
				if ("humidity".equals(child.getNodeName())) {
					wc.setHumidity(value);
				}
				if ("wind_condition".equals(child.getNodeName())) {
					wc.setWind(value);
				}
				if ("condition".equals(child.getNodeName())) {
					wc.setCondition(value);
				}
			}

			return wc;
		} catch (Exception e) {
			Logger.inst.error(e);
		}
		return null;
	}

	public static void main(String a[]) {
		Logger.inst.start();
		Position p = new Position(52.381454100000006, 4.8572771);

		System.out.println(getWeather(p));
	}

}
